package cn.aiyuan.controller;

import cn.aiyuan.domain.User;
import cn.aiyuan.service.UserService;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import cn.hutool.core.date.DateUtil;

/**
 * @author wangyuan
 * @date 2021/6/2
 */
@RestController
@RequestMapping("/api/aiyuan/user")
@Api(tags = "用户测试")
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation("保存用户")
    @PostMapping
    public R<Boolean> insert(@RequestBody User user) {
        return R.ok(userService.save(user));
    }

    @ApiOperation("批量保存用户")
    @GetMapping("/batch")
    public String insert(@RequestParam("round") int round,@RequestParam("timePerRound") int timePerRound) {


        if (round < 0 || round > 100) {
            return "round区间0-10";
        }

        if (timePerRound < 0 || timePerRound > 10000) {
            return "timePerRound区间 - 10000";
        }

        for (int i = 0; i < round; i++) {
            for (int j = 0; j <timePerRound; j++) {
                User user = new User();
                int[] arr = {1,2,3,5,6,7,8};
                long userId = new Snowflake(1, arr[j % 5]).nextId();
                user.setId(userId+1);
                user.setAge(j);
                user.setEmail(j + "@126.com");
                user.setName(j + "张");
                userService.save(user);
            }
        }

        return "新增"+round * timePerRound + "条";

    }

    @GetMapping("/all")
    public R<List<User>> selectAll() {
        return R.ok(userService.list());
    }

    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Long id) {
        return R.ok(userService.getById(id));
    }

    @GetMapping("/email")
    public R<User> getByEmail(@RequestParam("email") String email) {
        LambdaQueryWrapper<User> eq = new QueryWrapper<User>().lambda().eq(User::getEmail, email).last("limit 1");
        User one = userService.getOne(eq);
        return R.ok(one);
    }

    @GetMapping("/sum")
    public R<Integer> getById() {
        int count = userService.count();
        return R.ok(count);
    }
}
